package MovieGuessingGame.login;



import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import MovieGuessingGame.login.Owasp;



public class LoginDB
{
 /* the default framework is embedded*/
// private String framework = "embedded";
// private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
// private String protocol = "jdbc:derby:";
	private String framework = "derbyclient";
	private String driver = "org.apache.derby.jdbc.ClientDriver";
	private String protocol = "jdbc:derby://localhost:1527/";
 
 public static void main(String[] args)
 {
     new LoginDB().validate("user1","Iam*Iam#");
     System.out.println("Lookup in DB finished");
     
 }

 
 boolean validate(String userName,String password)
 {
     /* parse the arguments to determine which framework is desired*/

	 
     System.out.println("CreateDB starting in " + framework + " mode");
     boolean worked = false;
     /* load the desired JDBC driver */
     loadDriver();

     /* We will be using Statement and PreparedStatement objects for
      * executing SQL. These objects, as well as Connections and ResultSets,
      * are resources that should be released explicitly after use, hence
      * the try-catch-finally pattern used below.
      * We are storing the Statement and Prepared statement object references
      * in an array list for convenience.
      */
     Connection conn = null;

     try
     {
         Properties props = new Properties(); // connection properties
         // providing a user name and password is optional in the embedded
         // and derbyclient frameworks
         props.put("user", "DBUser");
         props.put("password", "K1ck1ForMe");

         /* By default, the schema APP will be used when no username is
          * provided.
          * Otherwise, the schema name is the same as the user name (in this
          * case "user1" or USER1.)
          *
          * Note that user authentication is off by default, meaning that any
          * user can connect to your database using any password. To enable
          * authentication, see the Derby Developer's Guide.
          */

         String dbName = "loginDB"; // the name of the database
         Owasp loginDB = new Owasp();
         

         /*
          * This connection specifies create=true in the connection URL to
          * cause the database to be created when connecting for the first
          * time. To remove the database, remove the directory derbyDB (the
          * same as the database name) and its contents.
          *
          * The directory derbyDB will be created under the directory that
          * the system property derby.system.home points to, or the current
          * directory (user.dir) if derby.system.home is not set.
          */
         conn = DriverManager.getConnection(protocol + dbName
                 + ";create=false", props);

         System.out.println("Connected to and created database " + dbName);

         // We want to control transactions manually. Autocommit is on by
         // default in JDBC.
         conn.setAutoCommit(false);


         try {
        	 worked = loginDB.authenticate(conn, userName,password);
        	 System.out.println("test db status " + worked);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

         if (framework.equals("embedded"))
         {
             try
             {
                 // the shutdown=true attribute shuts down Derby
                 DriverManager.getConnection("jdbc:derby:;shutdown=true");

                 // To shut down a specific database only, but keep the
                 // engine running (for example for connecting to other
                 // databases), specify a database in the connection URL:
                 //DriverManager.getConnection("jdbc:derby:" + dbName + ";shutdown=true");
             }
             catch (SQLException se)
             {
                 if (( (se.getErrorCode() == 50000)
                         && ("XJ015".equals(se.getSQLState()) ))) {
                     // we got the expected exception
                     System.out.println("Derby shut down normally");
                     // Note that for single database shutdown, the expected
                     // SQL state is "08006", and the error code is 45000.
                 } else {
                     // if the error code or SQLState is different, we have
                     // an unexpected exception (shutdown failed)
                     System.err.println("Derby did not shut down normally");
                     printSQLException(se);
                 }
             }
         }
     }
     catch (SQLException sqle)
     {
         printSQLException(sqle);
     } finally {
         // release all open resources to avoid unnecessary memory usage

 
         //Connection
         try {
             if (conn != null) {
                 conn.close();
                 conn = null;
             }
         } catch (SQLException sqle) {
             printSQLException(sqle);
         }
     }
     return worked;
 }

 /**
  * Loads the appropriate JDBC driver for this environment/framework. For
  * example, if we are in an embedded environment, we load Derby's
  * embedded Driver, <code>org.apache.derby.jdbc.EmbeddedDriver</code>.
  */
 private void loadDriver() {
     /*
      *  The JDBC driver is loaded by loading its class.
      *  If you are using JDBC 4.0 (Java SE 6) or newer, JDBC drivers may
      *  be automatically loaded, making this code optional.
      *
      *  In an embedded environment, this will also start up the Derby
      *  engine (though not any databases), since it is not already
      *  running. In a client environment, the Derby engine is being run
      *  by the network server framework.
      *
      *  In an embedded environment, any static Derby system properties
      *  must be set before loading the driver to take effect.
      */
     try {
         Class.forName(driver).newInstance();
         System.out.println("Loaded the appropriate driver");
     } catch (ClassNotFoundException cnfe) {
         System.err.println("\nUnable to load the JDBC driver " + driver);
         System.err.println("Please check your CLASSPATH.");
         cnfe.printStackTrace(System.err);
     } catch (InstantiationException ie) {
         System.err.println(
                     "\nUnable to instantiate the JDBC driver " + driver);
         ie.printStackTrace(System.err);
     } catch (IllegalAccessException iae) {
         System.err.println(
                     "\nNot allowed to access the JDBC driver " + driver);
         iae.printStackTrace(System.err);
     }
 }

 /**
  * Reports a data verification failure to System.err with the given message.
  *
  * @param message A message describing what failed.
  */
 private void reportFailure(String message) {
     System.err.println("\nData verification failed:");
     System.err.println('\t' + message);
 }

 /**
  * Prints details of an SQLException chain to <code>System.err</code>.
  * Details included are SQL State, Error code, Exception message.
  *
  * @param e the SQLException from which to print details.
  */
 public static void printSQLException(SQLException e)
 {
     // Unwraps the entire exception chain to unveil the real cause of the
     // Exception.
     while (e != null)
     {
         System.err.println("\n----- SQLException -----");
         System.err.println("  SQL State:  " + e.getSQLState());
         System.err.println("  Error Code: " + e.getErrorCode());
         System.err.println("  Message:    " + e.getMessage());
         // for stack traces, refer to derby.log or uncomment this:
         //e.printStackTrace(System.err);
         e = e.getNextException();
     }
 }

 
}